package top.test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Cache {
    private volatile Map<String, Integer> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //存储
    public void put(String key, Integer value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println("线程" + Thread.currentThread().getName() + "===存储" + value);
            map.put(key, value);
            System.out.println("线程" + Thread.currentThread().getName() + "===已存储");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    //读取
    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println("线程" + Thread.currentThread().getName() + "===读取");
            map.get(key);
            System.out.println("线程" + Thread.currentThread().getName() + "===已读取");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void clear() {
        map.clear();
    }

    /*public static void main(String[] args) {
        Cache cache = new Cache();
        for (int j = 0; j < 10000; j++) {
            cache.clear();
            Thread[] threads = new Thread[6];

            //存储
            for (int i = 0; i < 3; i++) {
                final Integer index = i;
                threads[i] = new Thread(() -> {
                    cache.put(index + "", index);
                }, String.valueOf(i));
                threads[i].start();
            }

            //读取
            for (int i = 3; i < 6; i++) {
                final Integer index = i;
                threads[i] = new Thread(() -> {
                    cache.get(index + "");
                }, String.valueOf(i));
                threads[i].start();
            }

            for (int i = 0; i < 6; i++) {
                try {
                    threads[i].join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("=====================");
        }
    }*/

    public static void main(String[] args) {
        Cache cache = new Cache();
        //存储
        for (int i = 1; i <= 3; i++) {
            final Integer index = i;
            new Thread(()->{
                cache.put(index+"",index);
            },String.valueOf(i)).start();
        }
        //读取
        for (int i = 1; i <= 3; i++) {
            final Integer index = i;
            new Thread(()->{
                cache.get(index+"");
            },String.valueOf(i)).start();
        }
    }
}
